import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:recipe/module/globalColor.dart';

import 'info.dart';
import 'module/api.dart';

class Favorate extends StatefulWidget {
  Favorate({Key key}) : super(key: key);
  @override
  _FavorateState createState() => _FavorateState();
}

class _FavorateState extends State<Favorate> {
  ScrollController _listController = ScrollController();
  bool listLoading = false;
  int curPage = 2;
  List faList = [
    {"foodTitle": '', "foodUrl": '', "foodSub": ''}
  ];
  @override
  void initState() {
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.instance.maskType = EasyLoadingMaskType.black;
    _listController.addListener(() {
      if (_listController.position.pixels >=
          _listController.position.maxScrollExtent) {
        if (curPage > 200) {
          EasyLoading.showToast('没有更多了');
          return;
        }
        if (!listLoading) {
          setState(() => {listLoading = true});
          EasyLoading.show(status: '加载中');
          getLikeList(curPage, 10).then((res) {
            setState(() {
              faList.addAll(res['data']);
              listLoading = false;
              EasyLoading.dismiss();
              curPage++;
            });
          });
        }
      }
    });

    getLikeList(1, 10).then((res) {
      setState(() {
        faList = res['data'];
        listLoading = false;
      });
    });
    super.initState();
  }

  // 获取收藏列表
  getLikeList(int curPage, int pageSize) async {
    String url = "like_list?curPage=${curPage}&pageSize=${pageSize}";

    try {
      var response = await HttpRequest.request(url, method: HttpRequest.GET);
      return response;
    } catch (e) {
      print(e);
    }
  }

  List<Widget> renderFavorateList(arr, context) {
    List<Widget> list = [];
    List.generate(
        arr.length,
        (index) => {
              list.add(
                InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) =>
                            Info(infoId: arr[index]['id'].toString()),
                      ),
                    );
                  },
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                            color: Colors.grey[200],
                            offset: Offset(1.0, 2.0), //阴影xy轴偏移量
                            blurRadius: 1.0, //阴影模糊程度
                            spreadRadius: 1.0 //阴影扩散程度
                            ),
                      ],
                    ),
                    padding: EdgeInsets.only(bottom: 10, top: 10),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(width: 10),
                        Container(
                          width: 150,
                          height: 80,
                          constraints:
                              BoxConstraints(maxWidth: 90, maxHeight: 90),
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(
                              Radius.circular(5),
                            ),
                            child: FadeInImage.assetNetwork(
                              placeholder: 'assets/images/cover.jpg',
                              fadeInDuration: const Duration(milliseconds: 500),
                              image: arr[index]["foodUrl"],
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        SizedBox(width: 15),
                        Container(
                          width: 250,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text(arr[index]["foodTitle"],
                                  maxLines: 3,
                                  textAlign: TextAlign.left,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                  )),
                              SizedBox(height: 5),
                              Text(arr[index]["foodSub"],
                                  maxLines: 3,
                                  textAlign: TextAlign.left,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: 13,
                                    fontWeight: FontWeight.w500,
                                  ))
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              )
            });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return faList[0]["foodTitle"] != ''
        ? Scaffold(
            appBar: AppBar(
              title: Text(
                "我的收藏",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 15,
                ),
              ),
            ),
            body: SingleChildScrollView(
              controller: _listController,
              padding: EdgeInsets.only(top: 25),
              child: Wrap(children: renderFavorateList(faList, context)),
            ))
        : Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(
                  valueColor: new AlwaysStoppedAnimation<Color>(
                      GlobalColor.themeColor)),
              SizedBox(height: 20),
              Text(
                "正在加载",
              )
            ],
          );
    ;
  }
}
